

package managedbean;

import java.io.Serializable;
import java.util.*;

import javax.ejb.EJB;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.naming.Context;
import javax.naming.InitialContext;

import jpa.CustomerJPA;
import ejb.CustomerFacadeRemote;

/**
 * Managed Bean ListClientsMBean
 */
@ManagedBean(name = "clients")
@SessionScoped
public class ListClientsMBean implements Serializable{
	
	private static final long serialVersionUID = 1L;	

	@EJB
	private CustomerFacadeRemote customerRemote;
	
	//stores all the instances of CustomerJPA
	private Collection<CustomerJPA> clientsList;
	//stores the screen number where the user is 
	private int screen = 0;
	//stores ten or fewer CustomerJPA instances that the user can see on a screen
	protected Collection<CustomerJPA> clientsListView;
	//stores the total number of instances of CustomerJPA
	protected int numberClients = 0;
	
	/**
	 * Constructor method
	 */
	public ListClientsMBean() throws Exception
	{
		this.clientList();
	}

	public String index(){
		return "homeView";
	}
	/**
	 * Method that returns an instance Collection of 10 or less PetJPA according screen 
	 * where the user is.
	 * @return Collection PetJPA
	 */
	public Collection<CustomerJPA> getClientsListView()
	{
		int n =0;
		clientsListView = new ArrayList<CustomerJPA>();
		for (Iterator<CustomerJPA> iter2 = clientsList.iterator(); iter2.hasNext();)
		{
			CustomerJPA client2 = (CustomerJPA) iter2.next();
			if (n >= screen*10 && n< (screen*10+10))
			{				
				this.clientsListView.add(client2);
			}
			n +=1;
		}
		this.numberClients = n;
		return clientsListView;
	}
	
	/**
	 * allows forward or backward in user screens
	 */
	public void nextScreen()
	{
		if (((screen+1)*10 < clientsList.size()))
		{
			screen +=1;
		}
	}
	public void previousScreen()
	{
		if ((screen > 0))
		{
			screen -=1;
		}
	}
	
	/**
	 * Method that gets a list of instances by category or all PetJPA
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private void clientList() throws Exception
	{	
		Properties props = System.getProperties();
		Context ctx = new InitialContext(props);
		screen = 0;
		customerRemote = (CustomerFacadeRemote) ctx.lookup("java:app/PracticalCaseStudyJEE.jar/CustomerFacadeBean!ejb.CustomerFacadeRemote");
		clientsList = (Collection<CustomerJPA>)customerRemote.findAllCustomers();
	}
}
